package com.szly.phm.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description : ${创建类}
 * @Author : chengjiang
 * @Date: 2021/2/3 19:33
 */
public class AreaCodeParserUtils {

    public static void isChildren(String parentCode, String childrenCode) {
        var p = parseCode(parentCode);
        var sb = new StringBuffer();
        int e = 1;
        int num = 1;
        if (!"00".equals(p.get("省"))) {
            sb.append(p.get("省"));
            e = 1;
            num++;
        }
        if (!"00".equals(p.get("市")) && num == 2) {
            sb.append(p.get("市"));
            e = 1;
            num++;
        }
        if (!"00".equals(p.get("县")) && num == 3) {
            sb.append(p.get("县"));
            e = 2;
            num++;
        }
        if (!"000".equals(p.get("乡")) && num == 4) {
            sb.append(p.get("乡"));
            e = 2;
            num++;
        }
        if (!"000".equals(p.get("村")) && num == 5) {
            sb.append(p.get("村"));
            e = 2;
        }
        var en = StringUtils.substringAfter(parentCode, sb.toString());
        if (e == 1) {
            en = en.substring(2, en.length());
        }
        if (e == 2) {
            en = en.substring(3, en.length());
        }
        if (!childrenCode.startsWith(sb.toString())) {
            throw new PcbsException("该区域行政编码应该以[" + sb.toString() + "]开头");
        }
        if (!childrenCode.endsWith(en)) {
            throw new PcbsException("该区域行政编码应该以[" + en + "]结尾");
        }
    }

    public static Map<String, String> parseCode(String areaCode) {
        areaCode = completionCode(areaCode);
        var map = new HashMap<String, String>();
        map.put("省", areaCode.substring(0, 2));
        map.put("市", areaCode.substring(2, 4));
        map.put("县", areaCode.substring(4, 6));
        map.put("乡", areaCode.substring(6, 9));
        map.put("村", areaCode.substring(9, 12));
        return map;
    }

    public static Integer areaLevel(String areaCode) {
        areaCode = completionCode(areaCode);
        //省
        if (areaCode.endsWith("0000000000")) {
            return 2;
        }
        //市
        if (areaCode.endsWith("00000000")) {
            return 3;
        }
        //县
        if (areaCode.endsWith("000000")) {
            return 4;
        }
        //乡
        if (areaCode.endsWith("000")) {
            return 5;
        }
        //村
        else return 6;
    }

    public static String completionCode(String areaCode) {
        return StringUtils.rightPad(areaCode, 12, "0");
    }

}
